//!@Author: DengLibin
//!@Date: Create in 2025-05-08 11:32:36
//!@Description:
//!

use std::{collections::HashMap, result};

use log::info;
use sqlx::{MySql, Pool};

use crate::{
    app,
    dao::mysql::{dictionary_info_dao, file_path_dao},
    sys::global::GlobalResult,
};

///@Author: DengLibin
///@Date: Create in 2025-05-08 11:43:33
///@Description: 给文件设置字典值
pub async fn deal_file_path_dic(file_path_table_name: &str, start_id: i64) -> GlobalResult<()> {
    let app_state = app::init().await?;

    let tree_name_id_map = get_dic_tree_name_id_map(&app_state.pool).await?;

    let mut start_id = start_id;
    let mut count = 0;
    loop {
        let file_paths =
            file_path_dao::limit_by_id(start_id, 100, file_path_table_name, &app_state.pool)
                .await?;
        if file_paths.is_empty() {
            break;
        }
        start_id = file_paths.last().unwrap().id;

        for ele in file_paths.iter() {
            let mut tree_dic_names = String::new();
            let pp = ele.path.replace("\\", "/");
            let mut dic_id = 0_i64;
            for (tree_name, id) in tree_name_id_map.iter() {
                //路径包含字典名称 当前字典名称比上次匹配的要长
                if pp.contains(tree_name) && tree_name.contains(&tree_dic_names) {
                    tree_dic_names = tree_name.clone();
                    dic_id = *id;
                }
            }
            if dic_id ==0_i64 {
                continue;
            }
            //更新dic_id
            file_path_dao::update_dic_id(
                ele.id,
                &dic_id.to_string(),
                file_path_table_name,
                &app_state.pool,
            )
            .await?;
        }

        count = count + file_paths.len();
        info!("进度:{}", count);
    }
    log::info!("完成! 数量:{}", count);

    result::Result::Ok(())
}

pub async fn get_dic_tree_name_id_map(pool: &Pool<MySql>) -> GlobalResult<HashMap<String, i64>> {
    let dic_infos = dictionary_info_dao::get_all(pool).await?;
    //转map
    let id_name_map = dic_infos
        .iter()
        .map(|dic| (dic.id, &dic.name))
        .collect::<HashMap<i64, &String>>();
    //tree_names_id_map
    let tree_name_id_map = dic_infos
        .iter()
        .map(|dic| {
            let mut tree_names = String::new();
            
            let mut is_first = true;
            for ele in dic.tree_num.replace("--", "-").split("-") {
                if ele.trim().is_empty() {
                    continue;
                }
                if is_first { //第一个节点不要
                    is_first = false;
                    continue;
                }

                let dic_id = ele.parse::<i64>().unwrap();
                let dic_name_o = id_name_map.get(&dic_id);
                if let Some(dic_name) = dic_name_o {
                    tree_names.push_str(dic_name);
                    tree_names.push_str("/");
                }else {
                    log::warn!("字典id不存在:{}", dic_id);
                }
           
            }
            log::info!("字典名称:{}", tree_names);

            return (tree_names, dic.id);
        })
        .collect::<HashMap<String, i64>>();
    result::Result::Ok(tree_name_id_map)
}
